package com.fc.advbox.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.fc.advbox.common.ResponseJson;
import com.fc.advbox.controller.admin.BaseController;
import com.fc.advbox.dto.equipment.QueryEquipmentRequest;
import com.fc.advbox.dto.equipment.SimpleEquipmentDto;
import com.fc.advbox.entity.ContractEntity;
import com.fc.advbox.entity.EquipmentEntity;
import com.fc.advbox.service.IContractService;
import com.fc.advbox.service.IEquipmentService;
import com.fc.advbox.utils.Constant;
import com.fc.advbox.utils.RRException;
import com.fc.advbox.utils.validator.ValidatorUtils;
import com.fc.advbox.utils.validator.group.AddGroup;
import com.fc.advbox.utils.validator.group.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.swing.plaf.basic.BasicEditorPaneUI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by E7450 on 2018/6/21.
 */
@RestController
@RequestMapping("/api/equipment")
@Api(value="设备接口", tags={"设备接口"})
public class EquipmentController extends BaseController {

    @Autowired
    private IEquipmentService equipmentService;

    @Autowired
    private IContractService contractService;

    @ApiOperation(value = "POST -- 查询设备列表",
            notes = " REST 方式请求" +
                    "Request Body: <ul>" +
                    "<li><i>可选参数: code: 设备编码 模糊查询</i></li>" +
                    "<li><i>可选参数: name: 设备名称，设备编码 模糊查询</i></li>" +
                    "<li><i>可选参数: type: 设备类型，例如： WF-01, WF-02, WF-03, WF-04 </i></li>" +
                    "<li><i>可选参数: city: 地区, 例如：'Suzhou'</i></li>" +
                    "<li><i>可选参数: district: 区域， 模糊查询</i></li>" +
                    "<li><i>可选参数: status: 状态， open - 开放，可以出租  / renting - 租聘中/ maintaining - 维修中 / discard - 丢弃, 损坏</i></li>" +
                    "<li><i>可选参数: tenantId: 承租人ID</i></li>" +
                    "<li><i>可选参数: hasAgent: 是否已有代理商， N - 没有，Y-有，不传- 不做判断</i></li>" +
                    "<li><i>可选参数: hasChannel: 是否已有渠道商， N - 没有，Y-有，不传 - 不做判断</i></li>" +
                    "<li><i>默认参数: page: 1, 当前页，默认值1</i></li>" +
                    "<li><i>默认参数: limit: 每次查询个数，默认为20</i></li>" +
                    "</ul>",
            response = ResponseJson.class,
            httpMethod = "POST",
            consumes = "application/json",
            produces = "application/json",
            code = 200
    )
    @PostMapping("/list")
    @RequiresPermissions("api:equipment:view")
    public ResponseJson doQueryList(@RequestBody QueryEquipmentRequest queryEquipmentRequest) {
        Map<String, Object> params = queryEquipmentRequest.toMap();
        //校对并赋值 offset和limit
        calculatePagination(params);

        List<EquipmentEntity> equipmentList = equipmentService.queryList(params);
        return ResponseJson.success(equipmentList);
    }


    /**
     * 设备ID获取出租广告合同列表
     */
    @PostMapping("/contract/rents")
    @ApiOperation(value = "设备ID获取出租广告合同列表", httpMethod="POST",
            notes=" POST " +
                    "Request Body: <ul>" +
                    "<li><i>必填参数: equipmentId: 设备ID, Long型</i></li>" +
                    "<li><i>默认参数: offset: 偏移量, 默认为0</i></li>" +
                    "<li><i>默认参数: limit: 每次查询个数，默认为20</i></li>" +
                    "</ul>")
    @RequiresPermissions("api:equipment:view")
    public ResponseJson queryEquipmentList(@RequestBody JSONObject params){
        if(!params.containsKey("equipmentId") || params.get("equipmentId") == null)
        {
            throw new RRException("equipmentId不能为空!");
        }

        //校对并赋值 offset和limit
        calculatePagination(params);

        // 本次查询只查询广告出租合同
        params.put("contractType", Constant.ContractType.RENT.getValue());

        List<ContractEntity> contractEntityList = contractService.queryContractsByEquipmentId(params);
        return ResponseJson.success(contractEntityList);
    }

    @ApiOperation(value = "GET -- 查询简化的全部设备列表",
            notes = " 仅在地图上使用，不分页，只包含编码和经纬度和状态。" +
                    "Request Parameter: <ul>" +
                    "<li><i>可选参数: city: 城市, 例如：'苏州'</i></li>" +
                    "<li><i>可选参数: district: 区域，例如：'虎丘区' 模糊查询</i></li>" +
                    "</ul>",
            response = ResponseJson.class,
            httpMethod = "GET",
            consumes = "application/json",
            produces = "application/json",
            code = 200
    )
    @GetMapping("/list/simple")
    @RequiresPermissions("api:equipment:view")
    public ResponseJson doQuerySimpleList(
            @RequestParam(name="city") String city,
            @RequestParam(name="district", required=false) String district) {
        Map<String, Object> reqParam = new HashMap<>();
        if(city!=null && !"".equals(city)){
            reqParam.put("city",city);
        }
        if(district!=null && !"".equals(district)){
            reqParam.put("district",district);
        }
        List<SimpleEquipmentDto> equipmentList = equipmentService.querySimpleList(reqParam);
        return ResponseJson.success(equipmentList);
    }


    @ApiOperation(value = "GET -- 查看单个设备信息",
            notes = " REST 方式请求" +
                    "/info/{equipmentId}",
            response = ResponseJson.class,
            httpMethod = "GET",
            consumes = "application/json",
            produces = "application/json",
            code = 200
    )
    @GetMapping("/info/{equipmentId}")
    @RequiresPermissions("api:equipment:view")
    public ResponseJson doQueryInfo(@PathVariable("equipmentId") Long equipmentId) {

        if(equipmentId == null || equipmentId == 0)
        {
            throw new RRException("ID不能为空!");
        }

        EquipmentEntity equipment = equipmentService.queryObject(equipmentId);
        return ResponseJson.success(equipment);
    }

    @ApiOperation(value = "POST -- 保存设备信息",
            notes = " REST 方式请求" +
                    "Request Body: <ul>" +
                    "<li><i>code: 设备编码 模糊查询</i></li>" +
                    "<li><i>name: 设备名称，设备编码 模糊查询</i></li>" +
                    "<li><i>type: 设备类型，例如： WF-01, WF-02, WF-03, WF-04 </i></li>" +
                    "<li><i>city: 地区, 例如：'Suzhou'</i></li>" +
                    "<li><i>district: 区域， 模糊查询</i></li>" +
                    "<li><i>status: 状态， open - 开放，可以出租  / renting - 租聘中/ maintaining - 维修中 / discard - 丢弃, 损坏</i></li>" +
                    "<li><i>buildDate: 安装时间 格式：yyyy-MM-dd HH:mm:SS 例如 2018-06-19 07:54:01</i></li>" +
                    "<li><i>latitude: 经度</i></li>" +
                    "<li><i>latitude: 纬度</i></li>" +
                    "<li><i>cost: 设备成本</i></li>" +
                    "<li><i>tenantId: 承租人ID</i></li>" +
                    "<li><i>rentStartDate: 当前时间下 租期开始时间</i></li>" +
                    "<li><i>rentEndDate: 当前时间下 租期结束时间</i></li>" +
                    "<li><i>attrs: 额外属性列表</i></li>" +
                    "</ul>",
            response = ResponseJson.class,
            httpMethod = "POST",
            consumes = "application/json",
            produces = "application/json",
            code = 200
    )
    @PostMapping("/save")
    @RequiresPermissions("api:equipment:save")
    public ResponseJson doSave(@RequestBody EquipmentEntity equipment) {
        ValidatorUtils.validateEntity(equipment, AddGroup.class);
        equipmentService.save(equipment);
        return ResponseJson.success();
    }

    @ApiOperation(value = "PUT -- 更新设备信息",
            notes = " REST 方式请求" +
                    "Request Body: <ul>" +
                    "<li><i>code: 设备编码 模糊查询</i></li>" +
                    "<li><i>name: 设备名称，设备编码 模糊查询</i></li>" +
                    "<li><i>type: 设备类型，例如： WF-01, WF-02, WF-03, WF-04 </i></li>" +
                    "<li><i>city: 地区, 例如：'Suzhou'</i></li>" +
                    "<li><i>district: 区域， 模糊查询</i></li>" +
                    "<li><i>status: 状态， open - 开放，可以出租  / renting - 租聘中/ maintaining - 维修中 / discard - 丢弃, 损坏</i></li>" +
                    "<li><i>buildDate: 安装时间 格式：yyyy-MM-dd HH:mm:SS 例如 2018-06-19 07:54:01</i></li>" +
                    "<li><i>latitude: 经度</i></li>" +
                    "<li><i>latitude: 纬度</i></li>" +
                    "<li><i>cost: 设备成本</i></li>" +
                    "<li><i>tenantId: 承租人ID</i></li>" +
                    "<li><i>rentStartDate: 当前时间下 租期开始时间</i></li>" +
                    "<li><i>rentEndDate: 当前时间下 租期结束时间</i></li>" +
                    "<li><i>attrs: 额外属性列表</i></li>" +
                    "</ul>",
            response = ResponseJson.class,
            httpMethod = "PUT",
            consumes = "application/json",
            produces = "application/json",
            code = 200
    )
    @PutMapping("/update")
    @RequiresPermissions("api:equipment:add")
    public ResponseJson doUpdate(@RequestBody EquipmentEntity equipment) {
        ValidatorUtils.validateEntity(equipment, UpdateGroup.class);
        equipmentService.update(equipment);
        return ResponseJson.success();
    }

    @ApiOperation(value = "POST -- 批量删除设备",
            notes = " REST 方式请求" +
                    "Request Body: <ul>")
    @PostMapping("/delete")
    @RequiresPermissions("api:equipment:edit")
    public ResponseJson doDetele(@RequestBody Long[] equipmentIds) {
        equipmentService.deleteBatch(equipmentIds);
        return ResponseJson.success();
    }
}
